<?php

namespace App\Supports\Qrcode;

use App\Models\User;
use App\Models\Product;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeNone;
use Endroid\QrCode\Writer\PngWriter;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;

class WapQrcode
{
	protected $inviter;
	protected $product = null;
	
	public function __construct(User $user, Product $product = null)
	{
		$this->inviter = $user;
		$this->product = $product;
	}
	
	protected function getQrcodeName()
	{
		if ($this->product) {
			$name = "qrcode-user-{$this->inviter->id}-product-{$this->product->id}.png";
		} else {
			$name = "qrcode-user-{$this->inviter->id}.png";
		}
		return $name;
	}
	
	protected function getLocalQrcodeDir()
	{
		$localPath = public_path('temp/wap-invite-qrcodes');
		if (! File::isDirectory($localPath)) {
			File::makeDirectory($localPath, 755, true, true);
		}
		return $localPath;
	}
	
	protected function getLocalQrcodeSavePath()
	{
		return $this->getLocalQrcodeDir() . '/' . $this->getQrcodeName();
	}
	
	protected function getRemoteQrcodeDir()
	{
		return 'images/wap-invite-qrcodes';
	}
	
	protected function getRemoteQrcodeSavePath()
	{
		return $this->getRemoteQrcodeDir() . '/' . $this->getQrcodeName();
	}
	
	protected function build(string $data)
	{
		return Builder::create()
			->writer(new PngWriter())->writerOptions([])
			->data($data)->encoding(new Encoding('UTF-8'))
			->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
			->size(300)->margin(10)->roundBlockSizeMode(new RoundBlockSizeModeNone())
			->build();
	}
	
	public function make(string $data)
	{
		if (Storage::exists($this->getRemoteQrcodeSavePath())) {
			return Storage::url($this->getRemoteQrcodeSavePath());
		}
		
		$qrcode = $this->build($data);
		$qrcode->saveToFile($this->getLocalQrcodeSavePath());
		
		// move to oss
		Storage::putFileAs($this->getRemoteQrcodeDir(), $this->getLocalQrcodeSavePath(), $this->getQrcodeName());
		
		// remove local poster
		File::delete($this->getLocalQrcodeSavePath());
		
		return Storage::url($this->getRemoteQrcodeSavePath());
	}
}
